package org.tulkas.test;

import java.net.BindException;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;

/**
 * @author <a href="mailto:tulkas.web@gmail.com">Tulkas</a>
 *
 */
public class TServer {
	public static final int START_PORT = 18080;

	private Handler handler = null;

	private Server server = null;

	public TServer setHandler(Handler handler) {
		this.handler = handler;
		return this;
	}

	public int start() throws Exception {
		int port = START_PORT;
		while (true) {
			try {
				server = new Server(port);
				if (handler != null)
					server.setHandler(handler);

				server.start();
			} catch (Exception e) {
				if (e instanceof BindException) {
					try {
						server.stop();
					} catch (Exception e1) {
					}
					server = null;
					port++;
					continue;
				} else {
					throw e;
				}
			}

			return port;
		}

	}

	public void stop() throws Exception {
		if (server != null && server.isRunning()) {
			server.stop();
		}
	}

	public void join() {
		if (server != null && server.isRunning()) {
			try {
				server.join();
			} catch (InterruptedException e) {
			}
		}
	}
}
